package com.tenton.servlet;

import com.tenton.pojo.Book;
import com.tenton.pojo.Orders;
import com.tenton.pojo.ShoppingCart;
import com.tenton.service.BookService;
import com.tenton.service.CartService;
import com.tenton.service.Impl.BookServiceImpl;
import com.tenton.service.Impl.CartServiceImpl;
import com.tenton.service.Impl.OrdersServiceImpl;
import com.tenton.service.OrdersService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Date: 2021/1/21
 * @Author: Tenton
 * @Description: 订单确认
 */
@WebServlet(name = "InsertOrdersServlet",urlPatterns = "/insertOrdersServlet")
public class InsertOrdersServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        OrdersService ordersService = new OrdersServiceImpl();
        BookService bookService = new BookServiceImpl();
        //获取当前用户Id
        HttpSession session = request.getSession();
        int userId = (int) session.getAttribute("userId");
        CartService cartService = new CartServiceImpl();
        //根据用户Id 获取购物车数据，即为订单数据
        List<ShoppingCart> carts = cartService.getCart(userId);
        String allPrices = request.getParameter("allPrice");
        //订单总价
        BigDecimal allPrice = new BigDecimal(allPrices);
        //地址
        String address = request.getParameter("address");
        //对地址进行转码操作
        address = new String(address.getBytes("iso-8859-1"),"utf-8");
        //图书Id
        String bookName = null;
        //购买数量
        Integer num = null;
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //当前时间，用于记录订单何时创建的
        Date date = new Date();
        String createTime = sdf.format(date);
        //创建一个ArrayList数组，用于保存订单数据
        List<Orders> list = new ArrayList<>();
        for (ShoppingCart cart : carts) {
            bookName = cart.getBookName();
            BigDecimal price = cart.getPrice();
            //商品总价
            BigDecimal totalPrice = cart.getTotalPrice();
            //购买数量
            num = cart.getNum();
            Book book = bookService.getBook(cart.getBookId());
            Integer bookNum = book.getNum();
            if (num <= bookNum) {
                bookNum = book.getNum() - num;
                Orders orders = new Orders(userId, bookName, price, num, totalPrice, allPrice, address, createTime);
                list.add(orders);
                book.setNum(bookNum);
                bookService.updateBook(book);
                cartService.deleteCart(cart.getId());
            }else {
                response.getWriter().print("商品数量不足，请删减购买数量，或购买其他商品，3秒后自动跳转到首页！");
                response.setHeader("Refresh", "3;URL=/listUserHomeServlet");
                return;
            }
        }
        ordersService.insertOrder(list);
        response.sendRedirect("/listOrdersServlet");
    }
}
